import React, { useCallback } from "react"

import { Field_FormSave, Field_name_id } from "@/components/utils/field.list"

import { FormProps } from "@/components/modal/form.modal"
import adminMangerService from "@/services/admin.manger.service"
import { FormRender } from "@whzhuke/antd"

import useForm from "antd/es/form/hooks/useForm"
import crypto from "crypto-js"

interface Props {
  values?: any
}
export const ResetPasswordManager: React.FC<Props & FormProps> = props => {
  const { values, onDone } = props
  const [form] = useForm<any>()
  const onFinish = useCallback(
    data => {
      const payload = { ...data }
      payload.oldPassword = crypto.MD5(payload.oldPassword).toString()
      payload.newPassword = crypto.MD5(payload.newPassword).toString()
      payload.rePassword = crypto.MD5(payload.rePassword).toString()
      adminMangerService["resetPwd"](payload)
        .then(res => {
          onDone?.()
        })
        .catch(err => {
          // 错误已经在拦截器中处理并显示，这里只需要确保错误被捕获
          // 不调用 onDone，让用户看到错误提示后可以继续修改
          console.error("修改密码失败:", err)
        })
    },
    [onDone]
  )
  return (
    <FormRender
      form={form}
      initialValues={{}}
      layout="horizontal"
      preserve={false}
      onFinish={onFinish}
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ width: 600 }}
      fieldList={[
        values ? Field_name_id : undefined,
        {
          fieldType: "input",
          formItemConfig: {
            required: true,
            name: "oldPassword",
            label: "旧密码"
          },
          config: { placeholder: "请输入旧密码", type: "password" }
        },
        {
          fieldType: "input",
          formItemConfig: {
            required: true,
            name: "newPassword",
            label: "新密码"
          },
          config: { placeholder: "请输入新密码", type: "password" }
        },
        {
          fieldType: "input",
          formItemConfig: {
            required: true,
            name: "rePassword",
            label: "确认密码"
          },
          config: { placeholder: "请输入确认密码", type: "password" }
        },
        { ...Field_FormSave, formItemConfig: { wrapperCol: { offset: 8, span: 16 } } }
      ]}
      autoComplete="off"
    />
  )
}
